<template>
  <a-modal
    class="formModal updateResume-dialog"
    :title="$t('form.updateResume.title')"
    v-model:open="modalVisible"
    @cancel="close"
    :footer="null"
    :closable="closable"
    :maskClosable="maskClosable"
  >
    <Swiper ref="SwiperRef" :allowTouchMove="false" :space-between="50">
      <SwiperSlide>
        <a-form ref="form1Ref" :model="formState">
          <div class="grid-container">
            <a-form-item
              :label="$t('form.updateResume.form_item_1_label')"
              name="last_name"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_1_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-input
                :maxlength="30"
                size="large"
                allowClear
                v-model:value.trim="formState.last_name"
              ></a-input>
            </a-form-item>
            <a-form-item
              :maxlength="30"
              :label="$t('form.updateResume.form_item_2_label')"
              name="first_name"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_2_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-input
                size="large"
                allowClear
                :maxlength="30"
                v-model:value.trim="formState.first_name"
              ></a-input>
            </a-form-item>
            <a-form-item
              :label="$t('form.updateResume.form_item_3_label')"
              name="sex"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_3_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-select
                v-model:value="formState.sex"
                :options="globalStore.sexTools.sexSelectOptions"
              ></a-select>
            </a-form-item>
            <a-form-item
              :label="$t('form.updateResume.form_item_4_label')"
              name="age"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_4_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-input-number  :min="0"  :max="150" v-model:value.trim="formState.age" />
            </a-form-item>
            <a-form-item
              :label="$t('form.updateResume.form_item_5_label')"
              name="country_id"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_5_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-select
                v-model:value="formState.country_id"
                show-search
                placeholder="Select a country"
                :options="countryStore.countrySelectOptions"
                :filter-option="filterOption"
                @search="saveCountrySelectValue"
              ></a-select>
            </a-form-item>
            <a-form-item
              :label="$t('form.updateResume.form_item_6_label')"
              name="address"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_6_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-input
                :maxlength="100"
                v-model:value.trim="formState.address"
                allowClear
              ></a-input>
            </a-form-item>
          </div>
        </a-form>
      </SwiperSlide>
      <SwiperSlide>
        <a-form ref="form2Ref" :model="formState" >
          <a-form-item
            :label="$t('form.updateResume.form_item_7_label')"
            name="language_id"
            :rules="[
              {
                required: true,
                message: $t('form.updateResume.form_item_7_error'),
                trigger: 'blur',
              },
            ]"
          >
            <div class="select-list">
              <div
                class="select-item"
                v-for="item in globalStore.languageList"
                :key="item.id"
                :class="
                  formState.language_id.includes(item.id + '') ? 'active' : ''
                "
                @click="selectCheckItem(item, 'language_id')"
              >
                <span v-html="item.title.replace(/\(/gi, '<br />(')"></span>
              </div>
            </div>
          </a-form-item>
          <a-form-item
            :label="$t('form.updateResume.form_item_8_label')"
            name="education_id"
            :rules="[
              {
                required: true,
                message: $t('form.updateResume.form_item_8_error'),
                trigger: 'blur',
              },
            ]"
          >
            <div class="select-list">
              <div
                class="select-item"
                v-for="item in globalStore.educationList"
                :key="item.id"
                :class="formState.education_id == item.id ? 'active' : ''"
                @click="selectCheckItem(item, 'education_id', false)"
              >
                {{ item.title }}
              </div>
            </div>
          </a-form-item>
          <a-form-item
            :label="$t('form.updateResume.form_item_9_label')"
            name="certificate_id"
            :rules="[
              {
                required: true,
                message: $t('form.updateResume.form_item_9_error'),
                trigger: 'blur',
              },
            ]"
          >
            <div class="select-list">
              <div
                class="select-item"
                v-for="item in globalStore.certificateList"
                :key="item.id"
                :class="
                  formState.certificate_id.includes(item.id + '')
                    ? 'active'
                    : ''
                "
                @click="selectCheckItem(item, 'certificate_id')"
              >
                {{ item.title }}
              </div>
            </div>
          </a-form-item>
        </a-form>
      </SwiperSlide>
      <SwiperSlide>
        <a-form ref="form3Ref" :model="formState" >
          <a-form-item
            :label="$t('form.updateResume.form_item_10_label')"
            name="airmodel_id"
            :rules="[
              {
                required: true,
                message: $t('form.updateResume.form_item_10_error'),
                trigger: 'blur',
              },
            ]"
          >
            <div class="select-list">
              <div
                class="select-item"
                v-for="item in globalStore.airModelList"
                :key="item.id"
                :class="
                  formState.airmodel_id.includes(item.id + '') ? 'active' : ''
                "
                @click="selectCheckItem(item, 'airmodel_id')"
              >
                {{ item.title }}
              </div>
            </div>
          </a-form-item>
        </a-form>
      </SwiperSlide>
    </Swiper>
    <div class="footer-btns">
      <a-button @click="close" v-if="cancelVisible && !isRegister">{{
        $t("btnText.cancel")
      }}</a-button>
      <a-button @click="skipClick" v-if="isRegister">{{
        $t("btnText.skip")
      }}</a-button>
      <a-button
        type="primary"
        @click="onClickPrevStep"
        v-if="currentStep != 0"
        >{{ $t("btnText.prev_step") }}</a-button
      >
      <a-button
        type="primary"
        @click="onClickNextStep"
        v-if="currentStep != 2"
        >{{ $t("btnText.next_step") }}</a-button
      >
      <a-button
        type="primary"
        v-if="currentStep == 2"
        :loading="isSubmitting"
        @click="submit"
        >{{ $t("btnText.save") }}</a-button
      >
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import {
  getCurrentInstance,
  nextTick,
  onBeforeUnmount,
  onMounted,
  ref,
  watch,
} from "vue";
import { postMemberInfo, postUpdateMemberInfo } from "../../../api/member";
import {
  useMemberStore,
  useGlobalStore,
  useCountryStore,
} from "../../../store";
import { message } from "ant-design-vue";
import type { UpdateMemberInfoParams } from "../../../types/member";

const saveCountrySelectValue = (v) => {
  if (v) {
    formState.value.country_id = v;
  }
};

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

type Props = {
  maskClosable: boolean;
  cancelVisible: boolean;
  closable: boolean;
  isRegister: boolean;
};
const props = withDefaults(defineProps<Props>(), {
  maskClosable: true,
  cancelVisible: true,
  closable: true,
  isRegister: false,
});

const form1Ref = ref();
const form2Ref = ref();
const form3Ref = ref();
const currentStep = ref(0);
const SwiperRef = ref();
const onClickPrevStep = () => {
  currentStep.value--;
  SwiperRef.value.$el.swiper.slidePrev();
};
const onClickNextStep = () => {
  if (currentStep.value == 0) {
    form1Ref.value.validate().then(() => {
      currentStep.value = 1;
      SwiperRef.value.$el.swiper.slideNext();
    });
  } else if (currentStep.value == 1) {
    form2Ref.value.validate().then(() => {
      currentStep.value = 2;
      SwiperRef.value.$el.swiper.slideNext();
    });
  }
};

// ===============store=======================
const memberStore = useMemberStore();
const globalStore = useGlobalStore();
const countryStore = useCountryStore();

const modalVisible = ref(false);
const close = () => {
  modalVisible.value = false;
  form1Ref.value.resetFields();
  form2Ref.value.resetFields();
  form3Ref.value.resetFields();
};
const skipClick = () => {
  close();
  nextTick(() => {
    goto("/new_profile/base");
  });
};


const { locale } = useI18n();
const show = () => {
  formState.value = {
    last_name: memberStore.profile?.last_name || "",
    first_name: memberStore.profile?.first_name || "",
    sex: globalStore.sexTools.getSexById(memberStore.profile?.sex) || "",
    age: memberStore.profile?.age || "",
    country_id:
      countryStore.getCountryById(memberStore.profile?.country_id) || "",
    education_id: memberStore.profile?.education_id || "",
    language_id: memberStore.profile?.language_id?.split(",") || [],
    certificate_id: memberStore.profile?.certificate_id?.split(",") || [],
    airmodel_id: memberStore.profile?.airmodel_id?.split(",") || [],
    address: memberStore.profile?.address,
  };
  modalVisible.value = true;
  nextTick(() => {
    initLabel();
    currentStep.value = 0;
    SwiperRef.value.$el.swiper.slideTo(0, 0);
  });
};

const initLabel = () => {
  let dom = document
    .querySelectorAll(".updateResume-dialog .ant-form .ant-form-item")[7]
    .querySelector(".ant-form-item-label label");
  dom.innerHTML = dom?.innerText.split(" ").join("<br/>");
};

defineExpose({
  close,
  show,
});

const filterOption = (input: string, option: any) => {
  return option.codes?.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// ===============form state================
const formRef = ref();
const formState = ref<UpdateMemberInfoParams>({
  last_name: "",
  first_name: "",
  sex: "",
  age: "",
  country_id: "",
  language_id: "",
  education_id: "",
  certificate_id: "",
  airmodel_id: "",
  address: "",
});

const selectCheckItem = (
  item: { id: number },
  key: string,
  flag: boolean = true
) => {
  if (flag) {
    let index = formState.value[key].findIndex(
      (value: string) => value == item.id + ""
    );
    if (index >= 0) {
      formState.value[key].splice(index, 1);
    } else {
      formState.value[key].push(item.id + "");
    }
  } else {
    formState.value[key] = item.id + "";
  }
};

const isSubmitting = ref(false);

const submit = () => {
  form3Ref.value.validate().then(async () => {
    let params = JSON.parse(JSON.stringify(formState.value));
    params.language_id = params.language_id
      .filter((item) => item != "")
      .join(",");
    params.certificate_id = params.certificate_id
      .filter((item) => item != "")
      .join(",");
    params.airmodel_id = params.airmodel_id
      .filter((item) => item != "")
      .join(",");
    if (isNaN(parseInt(params.sex))) {
      params.sex = globalStore.getSexIdBySexName(params.sex + "");
    }
    if (isNaN(parseInt(params.country_id))) {
      params.country_id = countryStore.getCountryIdByTitle(
        params.country_id + ""
      );
    }

    isSubmitting.value = true;
    let res = await postUpdateMemberInfo(params);
    if (res.code === 200) {
      let res2 = await postMemberInfo();
      isSubmitting.value = false;
      if (res2.code === 200) {
        memberStore.updateProfile(res2.data);
        message.success($t("message.changed_success"));
        if (props.isRegister) {
          skipClick();
        } else {
          close();
        }
      } else {
        message.error($t('message.error.update'));
      }
    } else {
      isSubmitting.value = false;
      message.error($t('message.error.update'));
    }
  });
};

const bindEvent = () => {
  modalVisible.value = false;
};
onMounted(() => {
  window.addEventListener("resize", bindEvent);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", bindEvent);
});
</script>
<style lang="less">
.updateResume-dialog {
  .ant-modal-content {
    padding: 24px 18px;
  }
  .footer-btns {
    padding: 0;
    padding-top: 12px;
  }
}
.ant-form {
  .ant-form-item-label {
    label {
      text-align: center;
      &::before {
        display: none !important;
      }
    }
  }
}
</style>

<style scoped lang="less">
.swiper {
  .swiper-slide {
    height: 0 !important;
    &.swiper-slide-active {
      height: auto !important;
    }
  }
}

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  column-gap: 20px;
}

.select-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  align-items: center;
  justify-items: center;
  gap: 11px;
  flex: 1;
  .select-item {
    width: 80px;
    height: 40px;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 10px;
    border: 1px solid #ccd6de;
    font-size: 12px;
    text-align: center;
    cursor: pointer;
    padding: 13px 9px;
    white-space: nowrap;
    line-height: 16px;
    word-break: break-all;
    &.active {
      background-color: #3d88f2;
      color: #fff;
    }
  }
}
</style>
